import React from 'react'
import {connect,} from 'react-redux'

import SharePopup from "./SharePopup/SharePopup"
import HeaderTitle from "./HeaderTitle/HeaderTitle"
import Versus from "./Versus/Versus"
import PlayBtn from "./PlayBtn/PlayBtn"
import {withRouter} from 'react-router-dom'
import {log} from "../../../../utils/commonfunc";
// styles
import './Header.css'
import {Icon} from "antd-mobile";
import liveBtnIcon from '../../../../res/images/web/game/game-video@2x.png'
import canvasBtnIcon from '../../../../res/images/web/game/game-cartoon@2x.png'

import VideoPlayer from "./VideoPlayer/VideoPlayer";
import {behaviorReq, fetchGameDetailReq, getGameLiveReq, getIsGameVodLiveReq, hitReq} from "../../../../apis/goApis";
import addRuleToIndex from "eslint-plugin-jsx-a11y/scripts/addRuleToIndex";
import Weather from "./Weather/Weather";
import cloudyBg from '../../../../res/images/web/game-room/game bg／cloudy@2x.png'
import fogBg from '../../../../res/images/web/game-room/game bg／fog@2x.png'
import rainBg from '../../../../res/images/web/game-room/game bg／rain@2x.png'
import snowBg from '../../../../res/images/web/game-room/game bg／snow@2x.png'
import sunnyBg from '../../../../res/images/web/game-room/game bg／sun@2x.png'
import LocalStorageService from "../../../../utils/LocalStorageService";
import {onTaskDone} from "../../../plan-detail/plan-detail";
import TaskDoneNotice from "../../../plan-detail/task-done-notice/task-done-notice";
import GoBackLayout from "../../../../layouts/GoBackLayout/GoBackLayout";
class GameRoomHeader extends React.Component {

    constructor(props) {
        super(props)
        this.videoRef = React.createRef()
        this.uid = LocalStorageService.get('userid')
        this.matchId = this.props.match.params.gameId
        this.state = {
            showSharePopup: false,
            playLive: false,
            gameCanvas: false,
            vod: false,
            vodSrcArr: [],
            vodSrc: '',
            vodIndex: 0,
            taskDone: false,
            taskInfo: '',
        }
    }

    componentDidMount() {
        this.getLive()
    }

    addHit = () => {
        const userid = LocalStorageService.get('userid')
        if (userid) {
            hitReq({
                userid,
                handle: 2,
            })
        }
    }

    getLive = () => {
        const isLogin = LocalStorageService.get('userid')
        if (isLogin) {
            behaviorReq({
                userid: LocalStorageService.get('userid'),
                handle: '足球比赛视频',
            })
        }
        return getIsGameVodLiveReq({matchId: parseInt(this.matchId),})
            .then(res => {

                const ret = res.data.ok
                if (ret) {
                    const index = this.state.vodIndex
                    const vodSrcArr = ret
                    const vodSrc = ret[index][1]
                    
                    this.setState({
                        vodSrcArr,
                        playLive: true,
                        vodSrc,
                    }, () => this.checkGameOnAndLogin())
                }
            })
    }

    checkGameOnAndLogin() {
        fetchGameDetailReq({matchid: parseInt(this.matchId),})
            .then(res => {
                try {
                    const detail = JSON.parse(res.data.ok)
                    const status = detail.info.statusid
                    const gameOn = status > 1 || status < 8
                    if (gameOn) {
                        if (LocalStorageService.get('userid')) {
                            return
                        } else {
                            this.props.history.push('../login')
                        }
                    }
                } catch (e) {
                    this.checkGameOnAndLogin()
                }

            })
    }

    playNext = () => {

        const index = this.state.vodIndex
        const arr = this.state.vodSrcArr
        const vodSrc = arr[index + 1][1]
        if (vodSrc) {
            this.setState({
                vodSrc,
                vodIndex: index + 1,
            })
        }

    }

    showShare = () => {
        this.setState({
            showSharePopup: true,
        })
    }

    hideSharePopup = () => {
        this.setState({
            showSharePopup: false,
        })
    }

    getCanvas = () => {
        this.props.cancelOnScroll()
        this.addHit()
        const isLogin = LocalStorageService.get('userid')
        if (isLogin) {
            behaviorReq({
                userid: LocalStorageService.get('userid'),
                handle: '足球比赛动画',
            })
        }
        this.setState({
            gameCanvas: true,
        })
    }

    getVodPlayer = () => {
        this.props.cancelOnScroll()
        this.addHit()
        const url = this.state.vodSrc
        this.getLive().then(() => {
            this.setState({
                vodSrc: url,
            }, () => {
                this.setState({
                    vod: true,
                })
            })
        })
        if (this.uid) {
            onTaskDone(this.uid, 'kbs')
                .then(data => {
                    if (data.Code === 0) {
                        this.setState({
                            taskDone: true,
                            taskInfo: data.Msg,
                        })
                    }
                })
        }

    }

    destroyPlayer = () => {
        this.setState({
            vod: false,
        })
    }

    getWeatherBG = (index) => {
        // 1:局部有云, 2:多云, 3:局部有云,雨, 4:雪, 5:晴, 6:阴有雨,局部有雷暴, 7:阴, 8:薄雾, 9:阴有雨, 10:多云有雨, 11:多云有雨,局部有雷暴, 12:局部有云,雨和雷暴, 13:雾；

        switch (index) {
            case 0:
                return ''
            case 1:
            case 2:
            case 3:
            case 7:
                return cloudyBg
            case 6:
            case 9:
            case 10:
            case 11:
                return rainBg
            case 4:
                return snowBg
            case 5:
                return sunnyBg
            case 8:
            case 13:
                return fogBg
            default:
                return ''
        }

    }

    render() {
        const game = this.props.game
        const info = game.info
        const env = info?.environment
        const atTop = this.props.atTop
        const normalCls = 'game-room-header-container'
        const foldedCls = 'game-room-header-container game-room-header-container-folded'

        let canvasClick = false
        let playLive = this.state.playLive
        const status = this.props.game.info.statusid

        if (status < 8) {
            canvasClick = true
        }

        if (status === 8) {
            canvasClick = false
            playLive = false
        }

        const vodBtn = <div
            className='game-room-header-icon-btn'
            onClick={this.getVodPlayer}
        >
            <img alt='' src={liveBtnIcon} />
            <span>视频</span>
        </div>
        const gap = <div className='game-room-header-icon-btn-gap'/>
        const canvasBtn = <div
            className='game-room-header-icon-btn'
            onClick={this.getCanvas}
        >
            <img alt='' src={canvasBtnIcon} />
            <span>动画</span>
        </div>

        const btns = <div
            className='flex-center-align-center'
            style={{
                position: 'absolute',
                bottom: '42px',
                left: '50%',
                transform: 'translateX(-50%)',
                background: 'rgba(0,0,0,0.3)',
            }}
        >
            {playLive ? vodBtn : null}
            {[playLive, canvasClick].every(x => x === true) ? gap : null}
            {canvasClick ? canvasBtn : null}
        </div>

        const topCtnStyle = {
            overflow: 'hidden',
            padding: 0,
            // position: 'fixed',
            // top: downloadShow ? 60 : 0,
            left: 0,
            zIndex: 999,
            height: 220,
            position: 'relative',
            width: window.innerWidth,
        }

        const canvas = <div
            className={normalCls}
            style={{...topCtnStyle}}
        >
            <Icon
                type='left'
                color='#fff'
                size='lg'
                style={{
                    position: 'absolute',
                    left: '10px',
                    top: '10px',
                    zIndex: 999,
                }}
                onClick={() => {
                    this.props.shouldOnScroll()
                    this.setState({
                        gameCanvas: false,
                    })
                }}
            />
            <iframe
                src={`http://123.207.85.242:3001/avatar/static/donghua/detail.html?id=${this.matchId}`}
                // src={`https://widget.namitiyu.com/leisu/mlive/m/detail.php?id=${this.matchId}`}
                style={{
                    height: '220px',
                    width: '100%',
                    borderWidth: 0,
                }}
            />

        </div>

        const player = <div
            style={{
                ...topCtnStyle,
            }}
        >
            <Icon
                type='left'
                color='#fff'
                size='lg'
                style={{
                    position: 'absolute',
                    left: '10px',
                    top: '10px',
                    zIndex: 999,
                }}
                onClick={() => {
                    this.props.shouldOnScroll()
                    this.setState({
                        vod: false,
                    })
                }}
            />
            <VideoPlayer
                atTop={atTop}
                videoSrc={this.state.vodSrc}
                videoSrcArr={this.state.vodSrcArr}
                vodIndex={this.state.vodIndex}
                playNext={this.playNext}
                destroyPlayer={this.destroyPlayer}
            />
        </div>



        const frame = <div
            style={{...topCtnStyle}}
        >
            <Icon
                type='left'
                color='#fff'
                size='lg'
                style={{
                    position: 'absolute',
                    left: '10px',
                    top: '10px',
                    zIndex: 999,
                }}
                onClick={() => {
                    this.setState({
                        playLive: false,
                    })
                }}
            />
            <iframe
                src={this.props.liveLink}
                style={{
                    height: '330px',
                    width: '100%',
                    marginTop: '-50px',
                }}
            />
        </div>
        if (this.state.vod) {
            return player
        }
        if (this.state.gameCanvas) {
            return canvas
        }

        const weatherId = info?.environment?.weather_id || 0
        const bgUrl = this.getWeatherBG(weatherId)

        const headerTemplate = (
            <div
                // className='game-room-header-container'
                className={
                    atTop
                    ? normalCls
                    : foldedCls
                }
                style={{
                    background: bgUrl ? `no-repeat center/cover url("${bgUrl}")` : '',
                }}
            >

                <SharePopup
                    showSharePopup={this.state.showSharePopup}
                    hideSharePopup={this.hideSharePopup}
                    history={this.props.history}
                />

                <HeaderTitle
                    history={this.props.history}
                    showShare={this.showShare}
                    atTop={atTop}
                />

                <Versus
                    atTop={atTop}
                />

                {atTop ? <Weather atTop={atTop} env={env} /> : null}
                {atTop ? btns : null}
            </div>
        )
        return <>
            {this.state.taskDone && <TaskDoneNotice taskInfo={this.state.taskInfo} onCancel={() => this.setState({taskDone: false,})}/>}
            {headerTemplate}
        </>

    }

}

export default withRouter(GameRoomHeader)

// const mapState = state => ({
//     game: state.game.currentGame,
// })
// export default connect(mapState)(withRouter(GameRoomHeader))
